#include "mini2440Configuration.h"

//default constructor
mini2440Configuration::mini2440Configuration()
{
    m_serverIP = "0.0.0.0";
    m_serverPort = 0;

    m_screenInterval = 1000;
    m_screenTimeout = 1000;
    m_screenImageDir = "slides/";

    m_messageInterval = 1000;
    m_messageImageDir = "slides/";

    m_defaultPassword = "0";
    m_currentPassword = "0";

    m_autolock = 7;
    m_language = "English";
}

// xml config file read router
bool mini2440Configuration::loadConfig()
{
    QFile xmlFile("config.xml");

    if (!xmlFile.exists() || (xmlFile.error() != QFile::NoError)) {
        qDebug() << "ERROR: Unable to open config file";
        return false;
    }

    xmlFile.open(QIODevice::ReadOnly);
    QXmlStreamReader reader(&xmlFile);
    while (!reader.atEnd()) {
        reader.readNext();

        if (reader.isStartElement())
        {
            if (reader.name() == "server")
                parseServerInfo(reader);
            else if(reader.name() == "screensave")
                parseScreenSave(reader);
            else if(reader.name() == "messageslideshow")
                parseMessageSlideShow(reader);
            else if(reader.name() == "password")
                parsePassword(reader);
            else if(reader.name() == "other")
                parseOther(reader);
        }
    }

    if (reader.hasError()) {

       qDebug() << QString("Error parsing %1 on line %2 column %3: \n%4")
                .arg("config.xml")
                .arg(reader.lineNumber())
                .arg(reader.columnNumber())
                .arg(reader.errorString());
       xmlFile.close();
       return false;
    }
    xmlFile.close();
    return true;
}

void mini2440Configuration::parseServerInfo(QXmlStreamReader& reader)
{
    QXmlStreamAttributes attrs = reader.attributes();
    QStringRef serverIP = attrs.value("ip");
    bool valid;
    unsigned int temp = 0;
    if (!serverIP.isEmpty())
    {
        m_serverIP = serverIP.toString();
    }

    QStringRef port = attrs.value("port");
    if (!port.isEmpty())
    {
        temp = port.toString().toUInt(&valid);
        if (valid)
            m_serverPort = temp;
        //qDebug() << m_serverPort;
    }
}

void mini2440Configuration::parseScreenSave(QXmlStreamReader& reader)
{
    QXmlStreamAttributes attrs = reader.attributes();

    QStringRef timeout = attrs.value("timeout");
    bool valid;
    unsigned int temp = 0;
    if (!timeout.isEmpty())
    {
        temp = timeout.toString().toUInt(&valid);
        if (valid)
            m_screenTimeout = temp;
    }

    QStringRef interval = attrs.value("interval");
    if (!interval.isEmpty())
    {
        temp = interval.toString().toUInt(&valid);
        if (valid)
            m_screenInterval = temp;
    }

    QStringRef imagedir = attrs.value("imagedir");
    if (!imagedir.isEmpty())
    {
        m_screenImageDir = imagedir.toString();
    }
    return;
}

void mini2440Configuration::parseMessageSlideShow(QXmlStreamReader& reader)
{
    QXmlStreamAttributes attrs = reader.attributes();

    bool valid;
    unsigned int temp = 0;

    QStringRef interval = attrs.value("interval");
    if (!interval.isEmpty())
    {
        temp = interval.toString().toUInt(&valid);
        if (valid)
            m_messageInterval = temp;
    }

    QStringRef imagedir = attrs.value("imagedir");
    if (!imagedir.isEmpty())
    {
        m_messageImageDir = imagedir.toString();
    }
    return;
}


void mini2440Configuration::parsePassword(QXmlStreamReader& reader)
{
    QXmlStreamAttributes attrs = reader.attributes();

    QStringRef defaultPassword = attrs.value("default");
    if (!defaultPassword.isEmpty())
    {
        m_defaultPassword = defaultPassword.toString();
    }

    QStringRef currentPassword = attrs.value("current");
    if (!currentPassword.isEmpty())
    {
        m_currentPassword = currentPassword.toString();
    }
    return;
}

void mini2440Configuration::parseOther(QXmlStreamReader& reader)
{
    bool valid;
    unsigned int temp = 0;

    while (!reader.atEnd()) {
        reader.readNext();
        if (reader.isStartElement() && reader.name() == "autolock") {

            QXmlStreamAttributes attrs = reader.attributes();
            QStringRef value = attrs.value("value");
            if (!value.isEmpty()) {
                temp = value.toString().toUInt(&valid);
                if (valid)
                    m_autolock = temp;
            }
        } else if(reader.isStartElement() && reader.name() == "language") {

            QXmlStreamAttributes attrs = reader.attributes();
            QStringRef lang = attrs.value("name");
            if (!lang.isEmpty()) {
                m_language = lang.toString();
            }
        }
    }
    //qDebug() << m_autolock;
    return;
}

// xml config file write router
bool mini2440Configuration::saveConfig()
{
    //QMessageBox::about(0,"Path",QDir::currentPath());
    QFile xmlFile("config.xml");
    if (!xmlFile.open(QFile::ReadOnly | QFile::Text)) {
        qDebug() << "ERROR: Unable to open config file";
        return false;
    }
    QString errorStr;
    int errorLine;
    int errorColumn;

    if (!m_domDocument.setContent(&xmlFile, true,
                                &errorStr,
                                &errorLine,      // set content
                                &errorColumn))
    {
        qDebug() << "Parse error at line " << errorLine << ", column " << errorColumn << ":\n" << errorStr;
        return false;
    }
//Save Password
    QDomNodeList list1 = m_domDocument.elementsByTagName("password");
    QDomElement element=list1.at(0).toElement();                            // notes
    if (!element.isNull()) {
        element.setAttribute("current",m_currentPassword);
    }
//Save Other
    QDomNodeList list2 = m_domDocument.elementsByTagName("other");
    QDomElement element1=list2.at(0).toElement();                            // notes
    if (!element1.isNull()) {
        QDomElement oldTitleElement = element1.firstChildElement("autolock");
        QDomElement newTitleElement = m_domDocument.createElement("autolock");

        newTitleElement.setAttribute("value",m_autolock);
        element1.replaceChild(newTitleElement, oldTitleElement);

        QDomElement oldLanguageElement = element1.firstChildElement("language");
        QDomElement newLanguageElement = m_domDocument.createElement("language");
        newLanguageElement.setAttribute("name", m_language);
        element1.replaceChild(newLanguageElement, oldLanguageElement);
    }
//Save parseMessageSlideShow
    QDomNodeList list3 = m_domDocument.elementsByTagName("screensave");
    QDomElement element3=list3.at(0).toElement();                            // notes
    if (!element3.isNull()) {
        element3.setAttribute("interval",m_screenInterval);
        element3.setAttribute("timeout", m_screenTimeout);
    }

    xmlFile.close();
    // write file
    const int IndentSize = 4;           // khoang cach tab
    QFile xmlFile1("config.xml");
    if (!xmlFile1.open(QFile::WriteOnly | QFile::Text))
    {
        qDebug() << "Cannot write file config.xml:\n" << xmlFile1.errorString();
        return false;
    }

    QTextStream out(&xmlFile1);
    m_domDocument.save(out, IndentSize);
    xmlFile1.close();
//QMessageBox::about(0,"save",m_currentPassword)    ;
    return true;

}


QString mini2440Configuration::get_currentPass()
{
    return m_currentPassword;
}

void mini2440Configuration::set_currentPass(QString currentPass)
{
    //m_currentPassword = currentPass;
    //m_currentPassword = new char[currentPass.length()+1];
    m_currentPassword = currentPass;
}

void mini2440Configuration::resetPass()
{
    m_currentPassword = m_defaultPassword;
    this->saveConfig();
    //QMessageBox::about(0,"Reset",m_currentPassword)    ;
}

QString mini2440Configuration::get_language()
{
    return m_language;
}

void mini2440Configuration::set_language(QString language)
{
    m_language = language;
}

unsigned int mini2440Configuration::get_autolock()
{
    return m_autolock;
}

void mini2440Configuration::set_autolock(unsigned int autolock)
{
    m_autolock = autolock;
}

int mini2440Configuration::get_screenInterval()
{
    return m_screenInterval;
}

void mini2440Configuration::set_screenInterval(int screenInterval)
{
    m_screenInterval = screenInterval;
}

int mini2440Configuration::get_screenTimeout()
{
    return m_screenTimeout;
}

void mini2440Configuration::set_screenTimeout(int screenTimeout)
{
    m_screenTimeout = screenTimeout;
}

unsigned int mini2440Configuration::getServerPort()
{
    return m_serverPort;
}

QString mini2440Configuration::getServerIP()
{
    return m_serverIP;
}

QString mini2440Configuration::getScreenImageDir()
{
    return m_screenImageDir;
}

QString mini2440Configuration::getMessageImageDir()
{
    return m_messageImageDir;
}
